package com.ze.familyday.familyphotoframesquare;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONArray;
import org.json.JSONObject;

import com.mouse.customview.CustomToast;
import com.mouse.customview.MyListView;
import com.mouse.customview.MyListView.OnRefreshListener;
import com.ze.commontool.NetHelper;
import com.ze.commontool.SoundPlayComment;
import com.ze.familyday.familyphotoframesquare.R;
import com.ze.familydayverpm.userinfo.UserInfoManager;
import com.ze.model.ModelDataMgr;
import com.ze.model.PhotoModel.CommentInfo;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

public class CommentListActivity extends Activity {

	private MyListView mLvComment;
	private List<CommentInfo> mList = new ArrayList<CommentInfo>();
	private LinearLayout mLlLoadMore;
	private ProgressBar mPbLoading;
	private boolean flag = false;
	private String mId = "";
	//private String mType = "";
	private int mPage = 1;
	private String m_auth;
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_comment_list);
		mLvComment = (MyListView) findViewById(R.id.lvComment);
		mLlLoadMore = (LinearLayout) findViewById(R.id.llLoadMore);
		mPbLoading = (ProgressBar) findViewById(R.id.pbLoading);
		mLvComment.setAdapter(mAdapter);
		mLvComment.setonRefreshListener(onRefreshListener);
		mLvComment.setOnScrollListener(onScrollListener);
		mId = getIntent().getStringExtra("id");
		//mType = getIntent().getStringExtra("type");
		if (UserInfoManager.getInstance(this).getItem("m_auth") != null) {
			m_auth = UserInfoManager.getInstance(this).getItem("m_auth").getValue();
		}
		if (m_auth != null) {
			mPbLoading.setVisibility(View.VISIBLE);
			executorService.submit(new LoadingRunnable(0));
		}
	}
	

	@Override
	protected void onDestroy() {
		SoundPlayComment.getInstance().stop();
		super.onDestroy();
	}



	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if (mPbLoading.getVisibility() == View.VISIBLE) {
					mPbLoading.setVisibility(View.GONE);
				}
				if (msg.arg1 > 0) {
					mAdapter.notifyDataSetChanged();
				}else {
					CustomToast.show(CommentListActivity.this, "该帖子暂时没有人评论！");
				}
				break;
			case 1:
				if (mLlLoadMore.getVisibility() == View.VISIBLE) {
					mLlLoadMore.setVisibility(View.GONE);
				}
				if (msg.arg1 > 0) {
					mAdapter.notifyDataSetChanged();
					mLvComment.smoothScrollBy(300, 300);
					if (msg.arg1 < 5) {
						CustomToast.show(CommentListActivity.this, "没有更多评论了！");
					}
				}else {
					CustomToast.show(CommentListActivity.this, "没有更多评论了！");
				}
				break;
			case 2:
				mLvComment.onRefreshComplete();
				mAdapter.notifyDataSetChanged();
				if (msg.arg1 > 0) {
					
				}else {
					
					CustomToast.show(CommentListActivity.this, "该帖子暂时没有人评论！");
				}
				break;
			default:
				if (mPbLoading.getVisibility() == View.VISIBLE) {
					mPbLoading.setVisibility(View.GONE);
				}
				CustomToast.show(CommentListActivity.this, "加载评论失败了...");
				break;
			}
			super.handleMessage(msg);
		}
		
	};
	
	private class LoadingRunnable implements Runnable{
		
		private int mType;
		
		public LoadingRunnable(int type) {
			this.mType = type;
		}

		@Override
		public void run() {
			try {
				String response = NetHelper.getResponByHttpClient(getResources().getString(R.string.http_photo_disscuss_audio), 
						mId, m_auth, (mPage++) + "");
				JSONObject cJsonObject = new JSONObject(response);
				if (!cJsonObject.isNull("error") && cJsonObject.getInt("error") == 0) {
					JSONArray cArray = cJsonObject.getJSONArray("data");
					for (int j = 0; j < cArray.length(); j++) {
						cJsonObject = cArray.getJSONObject(j);
						CommentInfo commentInfo = new CommentInfo();
						if (!cJsonObject.isNull("authorname")) {
							commentInfo.authorname = cJsonObject.getString("authorname");
						}
						if (!cJsonObject.isNull("message")) {
							commentInfo.message = cJsonObject.getString("message");
						}
						if (!cJsonObject.isNull("dateline")) {
							commentInfo.dateline = cJsonObject.getString("dateline");
						}
						if (!cJsonObject.isNull("soundurl")) {
							commentInfo.soundurl = cJsonObject.getString("soundurl");
							if (commentInfo.soundurl != null && !commentInfo.soundurl.equals("")) {
								commentInfo.soundfile = ModelDataMgr.getInstance().downFile(commentInfo.soundurl, "");
							}
						}
						if (!cJsonObject.isNull("soundtime")) {
							commentInfo.soundtime = cJsonObject.getString("soundtime");
						}
						mList.add(commentInfo);
					}
					if (cArray != null) {
						if (cArray.length() >= 5) {
							flag = true;
						}
						Message message = new Message();
						message.what = mType;
						message.arg1 = cArray.length();
						mHandler.sendMessage(message);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				mHandler.sendEmptyMessage(10086);
			}
		}
	}
	
	private OnRefreshListener onRefreshListener = new OnRefreshListener() {
		
		@Override
		public void onRefresh() {
			mPage = 1;
			mList.clear();
			executorService.submit(new LoadingRunnable(2));
		}
	};
	
	private OnScrollListener onScrollListener = new OnScrollListener() {
		
		int visibleLastIndex;
		
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO onScrollStateChanged
			int itemsLastIndex = mAdapter.getCount() - 1;    //数据集最后一项的索引  
	        int lastIndex = itemsLastIndex + 1;             //加上底部的loadMoreView项  
	        if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {  
	        	if (flag) {
					flag = false;
					mLlLoadMore.setVisibility(View.VISIBLE);
					Animation commentTranAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,0.0f, 
							Animation.RELATIVE_TO_SELF, 1.0f, 
							Animation.RELATIVE_TO_SELF,0.0f);
					commentTranAnimation.setDuration(300);
					mLlLoadMore.startAnimation(commentTranAnimation);
					executorService.submit(new LoadingRunnable(1));
				}
	        } 
		}
		
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
	        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;  
		}
	};
	
	private BaseAdapter mAdapter = new BaseAdapter() {
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHoder hoder = null;
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(R.layout.comment_list_item, null);
				hoder = new ViewHoder();
				hoder.tvAuthorname = (TextView) convertView.findViewById(R.id.tvAuthorname);
				hoder.tvMessage = (TextView) convertView.findViewById(R.id.tvMessage);
				hoder.tvTime = (TextView) convertView.findViewById(R.id.tvTime);
				hoder.btSound = (Button) convertView.findViewById(R.id.btSound);
				hoder.btSound.setSelected(false);
				convertView.setTag(hoder);
			}else {
				hoder = (ViewHoder) convertView.getTag();
			}
			if (hoder != null) {
				final CommentInfo commentInfo = (CommentInfo) getItem(position);
				hoder.tvAuthorname.setText(commentInfo.authorname);
				if (commentInfo.soundurl != null && !commentInfo.soundurl.equals("")) {
					hoder.tvMessage.setVisibility(View.GONE);
					hoder.btSound.setVisibility(View.VISIBLE);
					hoder.btSound.setText(commentInfo.soundtime + " " +'"');
					hoder.btSound.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(final View v) {
							if (!v.isSelected()) {
								v.setSelected(true);
								SoundPlayComment.getInstance().start(commentInfo.soundfile);
								SoundPlayComment.mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
									
									@Override
									public void onCompletion(MediaPlayer mp) {
										v.setSelected(false);
										mp.stop();
										mp.release();
										SoundPlayComment.mediaPlayer = null;
									}
								});
							}else {
								v.setSelected(false);
								SoundPlayComment.getInstance().stop();
							}
						}
					});
				}else {
					hoder.btSound.setVisibility(View.GONE);
					hoder.tvMessage.setVisibility(View.VISIBLE);
					hoder.tvMessage.setText(commentInfo.message);
				}
				hoder.tvTime.setText(NetHelper.transTime(Long.parseLong(commentInfo.dateline)));
			}
			return convertView;
		}
		
		@Override
		public long getItemId(int position) {
			return 0;
		}
		
		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList == null ? 0 : mList.size();
		}
	};
	
	class ViewHoder{
		public TextView tvAuthorname;
		public TextView tvTime;
		public TextView tvMessage;
		public Button btSound;
	}

}
